package com.gyt.manager.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Pattern;

/**
 * @author v_yantgao
 */
@Slf4j
public class DateUtil {

    public static final String PATTERN_DATE_MILLS = "yyyy-MM-dd HH:mm:ss.SSS";

    /**
     * Date format pattern used to parse timestamp
     */
    public static final String PATTERN_DATE_SECOND = "yyyy-MM-dd HH:mm:ss";
    public static final String PATTERN_DATE_MINUTE = "yyyy-MM-dd HH:mm";
    public static final String PATTERN_DATE_HOUR = "yyyy-MM-dd HH";
    public static final String PATTERN_HOUR_MINUTE = "yyyyMMddHH:mm";
    /**
     * Date format pattern used to parse timestamp
     */
    public static final String PATTERN_DATE_DAY = "yyyy-MM-dd";
    public static final String PATTERN_ONLY_HOUR_MINUTE = "HH:mm";
    public static final String PATTERN_ONLY_HOUR = "HH";
    public static final String PATTERN_ONLY_DAY = "dd";
    public static final String PATTERN_ONLY_MINUTE = "mm";

    /**
     * 返回指定格式时间
     *
     * @param date   为null时，返回当前日期new Date()
     * @param format
     * @return
     */
    public static String getTimeByFormat(Date date, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        if (null == date) {
            return StringUtils.EMPTY;
        }
        return sdf.format(date);
    }

    /**
     * 返回当前时间
     */
    public static String getTimeOfNow() {
        SimpleDateFormat sdf = new SimpleDateFormat(PATTERN_DATE_SECOND);
        Calendar calendar = Calendar.getInstance();
        return sdf.format(calendar.getTime());
    }

    /**
     * 得到指定时间的时间戳
     */
    public static long getTransTime(String transTime, String format) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            Date d = sdf.parse(transTime);
            return d.getTime();
        } catch (Exception e) {
            log.error("parse error->", e);
        }
        return 0;
    }

}
